package com.hrhr74.penguinstream.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hrhr74.penguinstream.constant.UserConstant;
import com.hrhr74.penguinstream.domain.login.UserLogin;
import com.hrhr74.penguinstream.domain.po.User;
import com.hrhr74.penguinstream.mapper.UserMapper;
import com.hrhr74.penguinstream.service.LoginStrategy;
import com.hrhr74.penguinstream.utils.JwtTool;
import com.hrhr74.penguinstream.utils.Result;
import com.hrhr74.penguinstream.utils.WriteTokenToRedis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service(UserConstant.USERNAME_LOGIN)
public class UsernameLogin extends ServiceImpl<UserMapper, User> implements LoginStrategy {
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private  JwtTool jwtTool;

    @Autowired
    private  StringRedisTemplate stringRedisTemplate;
    @Autowired
    private  WriteTokenToRedis writeTokenToRedis;

    @Override
    public Result login(UserLogin userLogin) {
        if(userLogin.getUsername()==null || userLogin.getPassword()==null){
            return Result.error("不支持的登录方式");
        }
        //查询用户
        User user = lambdaQuery().eq(User::getUsername, userLogin.getUsername()).one();
        if(user == null){
            return Result.error("用户名或密码错误！");
        }
        if(!passwordEncoder.matches(userLogin.getPassword(), user.getPassword())){
            return Result.error("用户名或密码错误！");
        }

        //将token写入redis
        String key = UserConstant.LOGIN_KEY + user.getId();
        writeTokenToRedis.writeTokenToRedis(key, user.getId(), stringRedisTemplate);

        return Result.ok("登录成功!");
    }
}
